package com.example.springboot.config.mainifest;


import com.sun.tools.attach.*;

import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/10 14:38
 */
public class AfterJvmAgent {
    public static void agentmain(String agentArgs, Instrumentation inst) throws ClassNotFoundException, UnmodifiableClassException {
        System.out.println("premain invoke!");

        inst.addTransformer(new MyAfterJvmFileTransformer(), true);
        // 关键点->允许热部署
        inst.retransformClasses(Class.forName("com.example.springboot.controller.mainifest.AfterJvmManifest", false, ClassLoader.getSystemClassLoader()));
    }

    public static void main(String[] args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        for (VirtualMachineDescriptor vmd : list) {
            // 如果虚拟机的名称为 xxx 则 该虚拟机为目标虚拟机，获取该虚拟机的 pid
            // 然后加载 agent.jar 发送给该虚拟机
            System.out.println(vmd.displayName());
            if (vmd.displayName().equals("com.example.springboot.SpringbootApplication")) {
                // 拿到当前虚拟机
                VirtualMachine virtualMachine = VirtualMachine.attach(vmd.id());
                virtualMachine.loadAgent("-javaagent:F:\\IdeaProjects\\springboot\\target\\original-springboot-0.0.1-SNAPSHOT.jar");
                virtualMachine.detach();
            }
        }
    }
}
